﻿using System;
using System.Collections.Generic;

using System.Text;
using System.Xml.Serialization;
using imeem.library;

namespace imeem.api
{
    public class ItemSerializerFactory
    {
        private static Dictionary<string, XmlSerializer> _serializerMap;

        private static Dictionary<string, XmlSerializer> SerializerMap
        {
            get
            {
                if (_serializerMap == null)
                {
                    _serializerMap = new Dictionary<string, XmlSerializer>();
                }
                return _serializerMap;
            }
        }

        public static XmlSerializer GetSerializer(string itemType)
        {
            if (!SerializerMap.ContainsKey(itemType))
            {
                addSerializerForType(itemType);
            }
           
            return SerializerMap[itemType];
        }

        private static void addSerializerForType(string itemType)
        {
            XmlSerializer serializer = null;

            if (itemType == "music")
            {
                serializer = new XmlSerializer(typeof(MusicData));
            }
            else if (itemType == "video")
            {
                serializer = new XmlSerializer(typeof(VideoData));
            }
            else if (itemType == "photo")
            {
                serializer = new XmlSerializer(typeof(PhotoData));
            }
            else if (itemType == "musicPlaylist" || itemType == "videoPlaylist" || itemType == "photoPlaylist")
            {
                serializer = new XmlSerializer(typeof(PlaylistData));
            }
            else if (itemType == "user")
            {
                serializer = new XmlSerializer(typeof(UserData));
            }
            else
            {
                throw new ArgumentException("Invalid item type: " + itemType);
                // log instead of throw? otherwise, if imeem introduces new item type deserialization will fail.
            }
            
            SerializerMap.Add(itemType, serializer);
        }
    }
}
